<?php

namespace App\V3\V3_2_7\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\MaterielOtherChargesModel;
use App\V3\V3_2_7\Services\MaterielService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Models\MaterielModel;

class MaterielController extends BaseController
{
    public function materielInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//入库状态：1-全部 2-部分
            'in_storage_time' => 'date_format:Y-m-d H:i:s',//入库时间
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (empty($data['content'])) {
            return $this->fail('', '请填写采购内容');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['is_share_shelf_location'] = $this->isShareShelfLocation();
        $data['is_use_packages_components'] = $this->isUsePackagesComponents();
        $this->log('采购单入库', $data);
        return response()->json(MaterielService::materielInStorage($data));
    }

    /**
     * 采购列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/18 16:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|numeric|min:1',//页面大小
            'currentPage' => 'required|numeric|min:1',//当前页码
            'search_type' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6, 7, 8])
            ],
            'status' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]
        ], [
            'pageSize.required' => '参数`页面大小`缺失',
            'pageSize.numeric' => '参数`页面大小`仅能为数字',
            'pageSize.min' => '参数`页面大小`最小只能为1',
            'currentPage.required' => '参数`页码`缺失',
            'currentPage.numeric' => '参数`页码`仅能为数字',
            'currentPage.min' => '参数`页码`最小只能为1',
            'search_type.required' => '参数`搜索类型`缺失',
            'search_type.in' => '参数`搜索类型`不合法',
            'status.required' => '参数`状态`缺失',
            'status.in' => '参数`状态`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if (isset($request->start_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'start_time' => 'date_format:Y-m-d H:i:s',//页面
            ], [
                'start_time.date_format' => '开始时间格式错误，例：' . date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if (isset($request->end_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'end_time' => 'date_format:Y-m-d H:i:s',//页面
            ], [
                'end_time.date_format' => '结束时间格式错误，例：' . date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if ($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isSharePurchase()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        $data['user_id'] = $this->getMainUserId();
        $data['main_id'] = $this->getUserId();
        return $this->success(
            MaterielService::list($data, $userId)
        );
    }

    /**
     * 采购列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/18 16:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function newList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|numeric|min:1',//页面大小
            'currentPage' => 'required|numeric|min:1',//当前页码
            'search_type' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6, 7, 8])
            ],
            'status' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]
        ], [
            'pageSize.required' => '参数`页面大小`缺失',
            'pageSize.numeric' => '参数`页面大小`仅能为数字',
            'pageSize.min' => '参数`页面大小`最小只能为1',
            'currentPage.required' => '参数`页码`缺失',
            'currentPage.numeric' => '参数`页码`仅能为数字',
            'currentPage.min' => '参数`页码`最小只能为1',
            'search_type.required' => '参数`搜索类型`缺失',
            'search_type.in' => '参数`搜索类型`不合法',
            'status.required' => '参数`状态`缺失',
            'status.in' => '参数`状态`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if (isset($request->start_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'start_time' => 'date_format:Y-m-d H:i:s',//页面
            ], [
                'start_time.date_format' => '开始时间格式错误，例：' . date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if (isset($request->end_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'end_time' => 'date_format:Y-m-d H:i:s',//页面
            ], [
                'end_time.date_format' => '结束时间格式错误，例：' . date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if ($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isSharePurchase()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        $data['user_id'] = $this->getMainUserId();
        $data['main_id'] = $this->getUserId();
        return $this->success(
            MaterielService::newList($data, $userId)
        );
    }


    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键
        ], [
            'id.required' => '参数`采购单id`是必须的'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            MaterielService::payHistory($request->id)
        );
    }

    public function cancel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        return response()->json(
            MaterielService::cancel(
                $this->getMainUserId(),
                $data
            )
        );
    }

    /**
     * @重新下单
     * created 在 2021/11/26 10:53 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['purchase_no'] = self::createPurchaseNo();
        $res = MaterielService::addAgain(
            $this->getUserId(),
            $this->getMainUserId(),
            $data
        );
        if ($res['code'] === 0) {
            $logData = '采购单号:' . $data['purchase_no'] . '创建成功！';
            $this->log('采购单-重新下单', $data, $logData);
        }
        return response()->json($res);
    }

    //创建采购单号
    private function createPurchaseNo()
    {
        list($t1, $t2) = explode(' ', microtime());
        $str = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        $millisecond = substr($str, 10, 13);
        $date = 'CG' . date("YmdHis") . $millisecond . mt_rand(100000, 999999);

        return $date;
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['logTime'] = time();
        $this->operateLog('删除采购', $data, $data['logTime']);
        return response()->json(
            MaterielService::del($data)
        );
    }

    /**
     * @详细
     * created 在 2021/11/26 14:53 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        return $this->success(MaterielService::detail($data));
    }

    /**
     * @详细
     * created 在 2021/11/26 14:53 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function newMaterielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        return $this->success(MaterielService::newMaterielDetail($data));
    }

    /**
     * @最后采购订单详细
     * created 在 2023/5/29 14:53 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author zlf
     */
    public function lastMaterielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'supplier_customer_id' => 'required',//销售单主键
        ], [
            'supplier_customer_id.required' => '参数`客户id`缺失'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition = [];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        $lastMaterielInfo = MaterielModel::select('id')
            ->where([
                'delete_flag' => 0,
                'main_id' => $this->getMainUserId(),
                'supplier_customer_id' => $data['supplier_customer_id'],
            ])->orderBy('created_at', 'DESC')->first();

        if (empty($lastMaterielInfo['id'])) {
            return $this->fail('', '没有找到采购单信息');
        }
        $condition['id'] = $lastMaterielInfo['id'];
        return $this->success(MaterielService::detail($condition));
    }

    /**
     * @其他费用列表
     * created 在 2021/11/25 15:00 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function chargesList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' => 'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = MaterielOtherChargesModel::where('materiel_id', $data['materiel_id'])->get();
        return $this->success($model);
    }

    /**
     * @修改采购单
     * created 在 2021/11/25 14:09 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function addCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' => 'required|integer',//销售单主键id
            'money' => 'required|string',//其他费用
            'other_type_name' => 'required|string',//其他费用类型名称
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        $res = MaterielService::addCharges($data);
        if ($res['code'] === 0) {
            $this->operateLog('添加采购其他费用', $data, $data['created_at'], $res['data']);
            return success();
        } else {
            return response()->json($res);
        }
    }

    /**
     * @编辑其他费用
     * created 在 2021/11/25 14:48 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function editCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//其他费用主键id
            'money' => 'required|string',//其他费用
            'other_type_name' => 'string',//其他费用类型名称
            'other_remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $res = MaterielService::editCharges($data);
        if ($res['code'] === 0) {
            $this->log('修改采购其他费用', $data, $res['data']);
            return success();
        } else {
            return response()->json($res);
        }
    }

    /**
     * @付款
     * created 在 2021/11/25 15:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function payMaterielMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' => 'required|integer',//销售单主键
            'money' => 'required|string',//收款金额
            'pay_time' => 'required|date',//收款时间
            //'payer_account'=>'required|string',//收款账号
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//收款状态：1-全部 2-部分
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['pay_time'] = strtotime($data['pay_time']);
        $data['created_at'] = time();
        $res = MaterielService::payMaterielMoney($data);
        if ($res['code'] === 0) {
            $purchaseNo = MaterielModel::where('id', $data['materiel_id'])->value('purchase_no');
            $logData = '采购单号:' . $purchaseNo . '付款金额为' . $data['money'] . '元';
            $this->log('采购付款', $data, $logData);
        }
        return response()->json($res);
    }

    /**
     * @新建采购单
     * created 在 2021/11/23 15:52 创建
     * updated at 2022/05/25 16:04
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'supplier_customer_id' => 'required|integer',//供应商id
            'purchase_time' => 'required',//采购日期
            'materiel_content' => 'required',//采购商品
            'is_auto_out_storage' => [
                'required',
                Rule::In([0, 1]),
            ],//是否自动出库：0-否 1-是
            //'approver_id' =>'required|integer',//审批人
            'preferential_way' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//优惠方式;0:无;1:修改价格;2:折扣优惠;
            'preferential_money' => 'numeric|min:0',//优惠方式对应金额
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            'supplier_customer_id.required' => '请选择供应商',
            'supplier_customer_id.integer' => '供应商`ID`为整数',
            /*'approver_id.required' => '请选择审批人',
            'approver_id.integer' => '审批人`ID`为整数',*/
            'is_auto_out_storage.required' => '自动出库，参数缺失！',
            'is_auto_out_storage.in' => '自动出库参数值有误！',
            'materiel_content.required' => '请添加需采购的商品',
            'purchase_time.required' => '采购日期,不能为空！',
            'preferential_way.required' => '优惠方式,参数值不能为空！',
            'preferential_way.in' => '优惠方式,参数值错误！',
            'preferential_money.numeric' => '优惠金额为数字！',
            'preferential_money.min' => '优惠金额值最小为0.00元！',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        //验证商品信息
        $validReq = SELF::validGoodsContent(json_decode($data['materiel_content'], true));
        if (!empty($validReq)) return fail('', $validReq);
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['purchase_no'] = CommonService::getOrderNo(new MaterielModel, 'purchase_no', 'C');
        $data['remark'] = empty($data['remark']) ? '' : $data['remark'];

        return response()->json(MaterielService::add($data, $this->isUseShelf(), $this->isShareShelfLocation()));
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author SunWu
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//采购主键id
            'supplier_customer_id' => 'required|integer',//供应商id
            'purchase_time' => 'required',//采购日期
            'materiel_content' => 'required',//采购商品
            'is_auto_out_storage' => [
                'required',
                Rule::In([0, 1]),
            ],//是否自动出库：0-否 1-是
            //'approver_id' =>'required|integer',//审批人
            'preferential_way' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//优惠方式;0:无;1:修改价格;2:折扣优惠;
            'preferential_money' => 'numeric|min:0',//优惠方式对应金额
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            'id.required' => '采购主键缺失！',
            'id.integer' => '采购主键`ID`为整数',
            'supplier_customer_id.required' => '请选择供应商',
            'supplier_customer_id.integer' => '供应商`ID`为整数',
            /*'approver_id.required' => '请选择审批人',
            'approver_id.integer' => '审批人`ID`为整数',*/
            'is_auto_out_storage.required' => '自动出库，参数缺失！',
            'is_auto_out_storage.in' => '自动出库参数值有误！',
            'materiel_content.required' => '请添加需采购的商品',
            'purchase_time.required' => '采购日期,不能为空！',
            'preferential_way.required' => '优惠方式,参数值不能为空！',
            'preferential_way.in' => '优惠方式,参数值错误！',
            'preferential_money.numeric' => '优惠金额为数字！',
            'preferential_money.min' => '优惠金额值最小为0.00元！',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        //验证商品信息
        $validReq = SELF::validGoodsContent(json_decode($data['materiel_content'], true));
        if (!empty($validReq)) return fail('', $validReq);
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        return response()->json(MaterielService::edit($data, $this->isUseShelf(), $this->isShareShelfLocation()));
    }

    /**
     * 验证商品信息
     * @param unknown $data
     * @return \Illuminate\Http\JsonResponse
     */
    static private function validGoodsContent($data)
    {
        foreach ($data as $vData) {
            //参数验证
            $validator = Validator::make($vData, [
                'type_id' => 'required|integer',//商品id
                'materiel_name' => 'required',//商品名称
                'unit_price' => 'required',//采购成本价
                'num' => 'numeric|min:0',//采购数量
                /*   'storage_id' => 'required|integer',//仓库id
                   'shelf_id' =>'required|integer',//货架id
                   'location_id' =>'required|integer',//库位id*/
            ], [
                'type_id.required' => '请选择商品',
                'type_id.integer' => '商品`ID`为整数',
                /* 'storage_id.required' => '请选择仓库',
                 'storage_id.integer' => '仓库`ID`为整数',
                 'shelf_id.required' => '请选择货架',
                 'shelf_id.integer' => '货架`ID`为整数',
                 'location_id.required' => '请选择库位',
                 'location_id.integer' => '库位`ID`为整数',*/
                'unit_price.required' => '成本价，不能为空',
                'num.numeric' => '采购数量为数字！',
                'num.min' => '采购数量最小值为0',
            ]);
            //参数错误响应
            if ($info = $validator->errors()->first()) {
                return $info;
            }
        }
    }
}
